const app = getApp();

Page({
  data: {
    order: null,
    statusClass: '',
    formattedTimes: {
      createdAt: '',
      meetingTime: ''
    }
  },

  onLoad(options) {
    const { id } = options;
    if (id) {
      this.loadOrderDetail(id);
    }
  },

  // 加载订单详情
  async loadOrderDetail(orderId) {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/orders/${orderId}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${wx.getStorageSync('token')}`
          },
          success: resolve,
          fail: reject
        });
      });

      if (res.statusCode === 200 && res.data.success) {
        const order = res.data.data.order;
        const statusClass = order.status === '已取消' ? 'canceled' : 
                          order.status === '已完成' ? 'completed' : '';
        
        // 预先格式化所有时间
        const formattedTimes = {
          createdAt: this.formatTime(order.createdAt),
          meetingTime: this.formatTime(order.meetingInfo?.time)
        };

        this.setData({
          order,
          statusClass,
          formattedTimes
        });
      } else {
        throw new Error(res.data.message || '获取订单详情失败');
      }
    } catch (error) {
      console.error('获取订单详情失败：', error);
      wx.showToast({
        title: '获取订单详情失败',
        icon: 'none'
      });
    }
  },

  // 确认交易完成
  async onConfirmTrade() {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/orders/${this.data.order._id}/status`,
          method: 'PUT',
          header: {
            'Authorization': `Bearer ${wx.getStorageSync('token')}`,
            'Content-Type': 'application/json'
          },
          data: {
            status: '已完成'
          },
          success: resolve,
          fail: reject
        });
      });

      if (res.statusCode === 200 && res.data.success) {
        wx.showToast({
          title: '交易完成',
          icon: 'success'
        });
        // 重新加载订单详情
        await this.loadOrderDetail(this.data.order._id);
      }
    } catch (error) {
      console.error('确认交易失败：', error);
      wx.showToast({
        title: '确认交易失败',
        icon: 'none'
      });
    }
  },

  // 取消交易
  onCancelTrade() {
    wx.showModal({
      title: '取消交易',
      content: '确定要取消这笔交易吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const res = await new Promise((resolve, reject) => {
              wx.request({
                url: `${app.globalData.baseUrl}/api/orders/${this.data.order._id}/status`,
                method: 'PUT',
                header: {
                  'Authorization': `Bearer ${wx.getStorageSync('token')}`,
                  'Content-Type': 'application/json'
                },
                data: {
                  status: '已取消',
                  reason: '用户主动取消'
                },
                success: resolve,
                fail: reject
              });
            });

            if (res.statusCode === 200 && res.data.success) {
              wx.showToast({
                title: '已取消交易',
                icon: 'success'
              });
              // 重新加载订单详情
              await this.loadOrderDetail(this.data.order._id);
            }
          } catch (error) {
            console.error('取消交易失败：', error);
            wx.showToast({
              title: '取消交易失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 跳转到商品详情
  navigateToProduct() {
    wx.navigateTo({
      url: `/pages/product/product?id=${this.data.order.product._id}`
    });
  },

  // 格式化时间
  formatTime(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
  }
}); 